<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 抖音用户
 */
class Ttink extends Api
{

    private $appid = 'ttbe30c88d2101be9d01';
    private $salt = 'qBMlIt6RvEuukNQU3YHvBkAVE1XaR7XsqfSmvVxd';
    private $token='tuIyXiQ6wc8MOgNe';


    protected $noNeedLogin = ['*'];

    /**
     * @return 用户openid
     */
    public function getopenid(){

        $code=$this->request->param('code');;
        $anonymousCode=$this->request->param('anonymousCode');

        if (empty($code)) {
            $this->error('请传入正确参数');
        }
        $url='https://developer.toutiao.com/api/apps/v2/jscode2session';
        $data=[
            'appid'=>'ttbe30c88d2101be9d01',
            'secret'=>'52a10ee46c71e44b5cfaf376e989d3d822f8f6d5',
            'code'=>$code,
            'anonymous_code'=>$anonymousCode,
        ];
        $res=$this->json_post($url,$data);

        $res=json_decode($res,true);


        $this->success('',$res);


    }


   public function json_post($url, $data = [])
    {
        //$data=http_build_query($data);
        //$data=json_encode($data);
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if(!$data){
            return 'data is null';
        }
        if(is_array($data))
        {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER,array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        $errorno = curl_errno($curl);
        if ($errorno) {
            return $errorno;
        }
        curl_close($curl);
        return $res;

    }




    public function DouyinPay(){


        $icon=$this->request->param('icon');
        $body = '抖音担保支付';
        $user=$this->auth->getUser();

        $money=Db::name('moneyset')->find();

        if ($icon==2){
            $zfmoney = $money['year'];
        }else{
            $zfmoney = $money['month'];
        }



        $orderno='tp'.date('ymdhis').rand(10,99);

        $outOrderNo =$orderno;//开发者侧的订单号
        $totalAmount = $zfmoney;//支付价格; 接口中参数支付金额单位为[分]
        $subject = $orderno; //商品描述也就是标题
        $body = $body;
        $validTimestamp = 60 * 60;//订单过期时间(秒);
        $notifyUrl = "https://bantonggou.vipwjf.com/api/ttink/notify"; //担保配置-设置回调地址
        //创建订单
        $response = $this->createOrder($outOrderNo, $totalAmount, $subject, $body, $validTimestamp, $notifyUrl);

        $logs['user_id']=$user['id'];
        $logs['types']=$icon;
        $logs['money']=$zfmoney;
        $logs['times']=time();
        $logs['payorder']=$orderno;

        Db::name('pay_vip')->data($logs)->insert();

        $this->success('成功',$response);
    }
    /**
     *	创建订单
     */
    public function CreateOrder($outOrderNo, $totalAmount, $subject, $body, $validTimestamp, $notifyUrl)
    {
        $params = [
            'app_id'       => $this->appid,//小程序appid
            'out_order_no' => $outOrderNo,
            'total_amount' => $totalAmount * 100,
            'subject'      => $subject,
            'body'         => $body,
            'valid_time'   => $validTimestamp,
            'notify_url'   => $notifyUrl,
        ];

        $params = array_filter($params);
        $params['sign'] = $this->sign($params);



        $res = $this->posts(
            'https://developer.toutiao.com/api/apps/ecpay/v1/create_order',
            $params
        );
        return $res;
    }
    /**
     *	获取签名
     */
    public  function sign($map) {
        $rList = [];
        foreach($map as $k =>$v) {
            if ($k == "other_settle_params" || $k == "app_id" || $k == "sign" || $k == "thirdparty_id")
                continue;

            $value = trim(strval($v));
            if (is_array($v)) {
                $value = $this->arrayToStr($v);
            }

            $len = strlen($value);
            if ($len > 1 && substr($value, 0,1)=="\"" && substr($value, $len-1)=="\"")
                $value = substr($value,1, $len-1);
            $value = trim($value);
            if ($value == "" || $value == "null")
                continue;
            $rList[] = $value;
        }
        $rList[] = $this->salt;//这里是SALT
        sort($rList, SORT_STRING);
        return md5(implode('&', $rList));
    }


    // **************** 以下方法 是字节小程序支付 签名处理方式
    public function callbackSign($data) {

        //***这里的是配置salt的时候填写的Token令牌

        $array = array(
            $this->token,(string)$data['timestamp'],(string)$data['nonce'],(string)htmlspecialchars_decode($data['msg'])
        );

        sort($array,SORT_STRING);

        $join_str = implode('',$array);

        return sha1($join_str);

    }


    public function arrayToStr($map) {
        $isMap =  $this->isArrMap($map);

        $result = "";
        if ($isMap){
            $result = "map[";
        }

        $keyArr = array_keys($map);
        if ($isMap) {
            sort($keyArr);
        }

        $paramsArr = array();
        foreach($keyArr as  $k) {
            $v = $map[$k];
            if ($isMap) {
                if (is_array($v)) {
                    $paramsArr[] = sprintf("%s:%s", $k, arrayToStr($v));
                } else  {
                    $paramsArr[] = sprintf("%s:%s", $k, trim(strval($v)));
                }
            } else {
                if (is_array($v)) {
                    $paramsArr[] = arrayToStr($v);
                } else  {
                    $paramsArr[] = trim(strval($v));
                }
            }
        }

        $result = sprintf("%s%s", $result, join(" ", $paramsArr));
        if (!$isMap) {
            $result = sprintf("[%s]", $result);
        } else {
            $result = sprintf("%s]", $result);
        }

        return $result;
    }

    public  function isArrMap($map) {
        foreach($map as $k =>$v) {
            if (is_string($k)){
                return true;
            }
        }

        return false;
    }

    public function posts(string $url, array $params = [], array $headers = [])
    {
        $headers[] = 'Content-type: application/json';

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        curl_close($ch);

        return json_decode($output, true);
    }



    public function notify()
    {


        Db::name('paylogs')->data(['text'=>'notify','date'=>date('y-m-d H:i:s')])->insert();

        $notify=file_get_contents("php://input");
        $notify=json_decode($notify,true);
        Db::name('paylogs')->data(['text'=>serialize($notify),'date'=>date('y-m-d H:i:s')])->insert();


        //  验签
        if ($notify['msg_signature'] !== $this->callbackSign($notify)) {
            return false;

        } else {
            //获取订单信息
            $order=(string)htmlspecialchars_decode($notify['msg']);
            $order = json_decode($order, true);
            //处理订单，获取订单号

            $sn =  $order['cp_orderno'];

            Db::name('paylogs')->data(['text'=>$sn,'date'=>date('y-m-d H:i:s')])->insert();
            $log=Db::name('pay_vip')->where(['payorder'=>$sn])->where(['status'=>0])->find();

            if($log){

                Db::name('pay_vip')->where(['payorder'=>$sn])->update(['status'=>1]);

                $uplod['level']=2;
                $user=Db::name('user')->where(['id'=>$log['user_id']])->find();

                $now=time();

                $btime=$now>$user['viper_time']?time():$user['viper_time'];

                if ($log['types']==1){
                    $uplod['viper_time']=$btime+2592000;
                }else{
                    $uplod['viper_time']=$btime+31104000;
                }

                Db::name('user')->where(['id'=>$log['user_id']])->update($uplod);

            }

        }



        echo json_encode(['err_no'=>0,'err_tips'=>'success']);
        die;

    }



    //单个购买.

    public function paysone(){

        $id=$this->request->param('id');

        $body = '抖音担保支付';
        $user=$this->auth->getUser();


        $money=Db::name('moneyset')->find();
        $zfmoney=$money['ones'];

        $orderno='to'.date('ymdhis').rand(10,99);

        $outOrderNo =$orderno;//开发者侧的订单号
        $totalAmount = $zfmoney;//支付价格; 接口中参数支付金额单位为[分]
        $subject = $orderno; //商品描述也就是标题
        $body = $body;
        $validTimestamp = 60 * 60;//订单过期时间(秒);
        $notifyUrl = "https://bantonggou.vipwjf.com/api/ttink/notifyone"; //这里可以忽略，走字节跳动小程序 -支付 -担保配置-设置回调地址
        //创建订单
        $response = $this->createOrder($outOrderNo, $totalAmount, $subject, $body, $validTimestamp, $notifyUrl);

        $logs['user_id']=$user['id'];
        $logs['land_id']=$id;
        $logs['times']=time();
        $logs['payorder']=$orderno;
        Db::name('land_pay')->data($logs)->insert();


        $this->success('成功',$response);
    }


    public function notifyone()
    {

        Db::name('paylogs')->data(['text'=>'notifyone','date'=>date('y-m-d H:i:s')])->insert();

        $notify=file_get_contents("php://input");
        $notify=json_decode($notify,true);
        Db::name('paylogs')->data(['text'=>serialize($notify),'date'=>date('y-m-d H:i:s')])->insert();



        //  验签
        if ($notify['msg_signature'] !== $this->callbackSign($notify)) {
            return false;

        } else {
            //获取订单信息
            $order=(string)htmlspecialchars_decode($notify['msg']);
            $order = json_decode($order, true);
            //处理订单，获取订单号

            $sn =  $order['cp_orderno'];

            Db::name('paylogs')->data(['text'=>$sn,'date'=>date('y-m-d H:i:s')])->insert();

            $log=Db::name('land_pay')->where(['payorder'=>$sn])->where(['status'=>0])->find();

            if($log){
                Db::name('land_pay')->where(['payorder'=>$sn])->update(['status'=>1]);

            }

        }




        echo json_encode(['err_no'=>0,'err_tips'=>'success']);
        die;
    }

}


